import { defineComponent, onMounted } from "vue";
import FTWidgetButton from "./widget-button";
import { PreviewUtils } from "@/utils/preview";

export default defineComponent({
  name: "FTPreviewWidget",
  components:{
    'ft-widget-button':FTWidgetButton
  },
  setup() {   
    const { initPreview, addHeadStyles, handleLinks } = PreviewUtils();
    let themeInfo = initPreview();
    const receiveMessage = (e: any): void => {
      if (e.data && e.data.name) {
        // 根据内容
        addHeadStyles(e.data.name);
        // themeSize在framework和Farris下都会有
        themeInfo.size = e.data.size;
        themeInfo.name = e.data.name;
        themeInfo.color = e.data.color;
      }
    };

    onMounted(() => {
      //处理样式链接
      handleLinks(themeInfo);
      const messageListener = receiveMessage.bind(this);
      window.removeEventListener("message", messageListener);
      // 捕获到message事件的时候，执行style的加载方法
      window.addEventListener("message", messageListener, false);
      // 通知父级，关闭loading
      window.parent.postMessage(
        { hideLoading: true },
        window.parent.location.href
      );
    });
    
    return () => (
      <>
       <ft-widget-button></ft-widget-button></>
    );
  }
});
